package school.valon.rest.core;

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import school.valon.UserContext;
import school.valon.business.UserBusiness;

//@PreMatching
public class ServiceFilter implements ContainerRequestFilter {

	@Autowired
	@Qualifier("userBusiness")
	private UserBusiness userBusiness;
	
	@Override
	public void filter(ContainerRequestContext requestContext) throws IOException {
        final SecurityContext securityContext =
                requestContext.getSecurityContext();
        //securityContext.getUserPrincipal()
	    if (securityContext == null ||
	    		securityContext.getUserPrincipal() == null) {
	    	requestContext.abortWith(Response.status(
					Response.Status.UNAUTHORIZED).entity("User cannot access the resource.").build());    	
	    } else {
			UserContext.setUser(
					userBusiness.getUserDtoByEmail(
							securityContext.getUserPrincipal().getName()));
	    }
	}

}
